package com.jf3q.front.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.common.domain.EduComment;
import com.jf3q.common.domain.EduMember;
import com.jf3q.common.domain.EduOrder;
import com.jf3q.common.exception.JfException;
import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.front.service.CommentService;
import com.jf3q.front.service.CourseService;
import com.jf3q.front.service.MemberService;
import com.jf3q.front.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    CommentService commentService;
    @Autowired
    CourseService courseService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    MemberService memberService;
    @Autowired
    OrderService orderService;


    //个人中心的评论列表  ——我的评论
    @Operation(summary = "查看评论列表")
    @GetMapping
    public ResultVo my(HttpServletRequest request,@RequestParam(defaultValue = "1")Integer pageNum,@RequestParam(defaultValue = Integer.MAX_VALUE+"") Integer pageSize) {
        String token = request.getHeader("token");

        if(!StringUtils.hasText(token)){
            throw new RuntimeException("token必传");
        }
        String userId = jwtTokenUtil.getUserIdByToken(token);
        LambdaQueryWrapper<EduComment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduComment::getMemberId,userId);
        queryWrapper.orderByDesc(EduComment::getEduCreate);

        Page<EduComment> page = commentService.page(new Page<>(pageNum, pageSize), queryWrapper);

        //把课程标题返回
        page.getRecords().stream().map(
                m -> {
                    m.setCourseTitle(courseService.getById(m.getCourseId()).getTitle());
                    return m;
                }
        ).collect(Collectors.toList());


        return ResultVo.success(page);


    }


    @Operation(summary = "添加评论")
    @PostMapping
    @Transactional
    public ResultVo save(@RequestBody EduComment comment, HttpServletRequest request) {

        if (!StringUtils.hasText(comment.getCourseId())) {

            throw new JfException(20001, "课程id必须传");
        }

        String token = request.getHeader("token");
        String memberId = jwtTokenUtil.getUserIdByToken(token);

        //只有购买过(或者报名过)该课程的人才能发评论（总之学习过该课程的人才有资格评价）
        LambdaQueryWrapper<EduOrder> lambdaQueryWrapper= new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(EduOrder::getCourseId,comment.getCourseId());
        lambdaQueryWrapper.eq(EduOrder::getMemberId,memberId);
        lambdaQueryWrapper.eq(EduOrder::getStatus,1);
        long count = orderService.count(lambdaQueryWrapper);
        if(count == 0){
            throw new JfException(20001, "只有购买过(或者报名过)该课程的人才能发评论");
        }

        //todo 看你要不要设计成只能评价一次（淘宝那种就是购买后的客户只能给评价一次或者追评啥的）

        comment.setMemberId(memberId);
        EduMember byId = memberService.getById(memberId);

        comment.setNickname(byId.getNickname());
        comment.setTeacherId(courseService.getById(comment.getCourseId()).getTeacherId());
        comment.setAvatar(byId.getAvatar());
        commentService.save(comment);
        return ResultVo.success();
    }
    @Operation(summary = "删除评论")
    @DeleteMapping("/{id}")
    public ResultVo del(@PathVariable  String id,HttpServletRequest request) {

        //只有是本人发布的评论的话才可以删除
        String token = request.getHeader("token");
        String memberId = jwtTokenUtil.getUserIdByToken(token);
        EduComment byId = commentService.getById(id);
        if (!byId.getMemberId().equals(memberId)) {
            throw new JfException(20001, "不是您发的评论不能删");
        }

        commentService.removeById(id);
        return ResultVo.success();
    }


}
